﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Yyd.Share.Base;

namespace Yyd.Share
{
    public class ValidateRequestActionFilterAttribute : ActionFilterAttribute
    {
        /*public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var modelState = context.ModelState;
                context.Result = new OkObjectResult(new ValidationFailedResultModel(
                    modelState.Keys
                        .SelectMany(key => modelState[key].Errors.Select(error => new ValidationError(key, error.ErrorMessage)))
                        .ToList()
                )
                {
                    Code = ReturnCode.ParamError
                });
            }
        }*/

        public override void OnResultExecuting(ResultExecutingContext context)
        {

            // 验证不通过,给出前端能识别出的提示，不再直接报错 偶然性网络不稳定，请重试
            if (!context.ModelState.IsValid)
            {
                var valid_key = context.ModelState.Keys.FirstOrDefault();
                var valid_msg = context.ModelState.Values.FirstOrDefault()?.Errors[0]?.ErrorMessage;
                var res = BaseResultModel.Failed("400", $"参数【{valid_key}】，{valid_msg}");
                context.Result = new OkObjectResult(res);
                return;
            }


            // 302跳转直接返回
            if (context.Result is RedirectResult) return;

            //文件流，也直接返回  lws2023-09-13
            if (context.Result is FileContentResult) return;

            #region 支付回调直接返回结果（字符串：SUCCESS）

            var requestPath = context.HttpContext.Request.Path.Value;
            var exceptRequest = new List<string>
            {
                "pay/paysuccessnotify"
            };
            if (!string.IsNullOrWhiteSpace(requestPath) && exceptRequest.Any(o => requestPath.Contains(o.ToLower())))
            {
                return;
            }

            #endregion

            // 如果是 ObjectResult，需要将结果转换成网关需要的格式
            var objectResult = context.Result as ObjectResult;
            if (objectResult?.Value is BaseResultModel)
            {
                return;
            }

            if (objectResult?.Value is IApiResult<object> apiResult)
            {
                var res = BaseResultModel.Succeed(
                    apiResult.OperateFlag ? ReturnCode.Success : ReturnCode.Failure,
                    apiResult.OperateMsg,
                    apiResult.GetData()
                );
                context.Result = new OkObjectResult(res);
                return;
            }

            context.Result = new OkObjectResult(BaseResultModel.Succeed(ReturnCode.Success, objectResult?.Value));
        }
    }
}